﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace TraitorAmongUs.Graphics {
	public class CharacterSprite : Sprite {
		protected double timePerRunningFrame;

		protected PlayerStates state;    // The sprite's current state
		public PlayerStates State {
			get {
				return state;
			}

			set {
				if(state != value) {
					currentFrame = 0;
					state = value;
				}
			}
		}

		public CharacterSprite(Texture2D tex)
			: base(tex) {
			Width = 32;
			Height = 64;
			State = PlayerStates.IDLE;
			timePerRunningFrame = 50.0;
		}

		public CharacterSprite(ContentManager content, string assetName)
			: base(content, assetName) {
			Width = 32;
			Height = 64;
			State = PlayerStates.IDLE;
			timePerRunningFrame = 50.0;
		}

		public override void Update(GameTime gameTime) {
			if(State == PlayerStates.IDLE) { // No animation for idle state
				timer = 0.0;
				currentFrame = 0;
				return;
			}

			timer += gameTime.ElapsedGameTime.TotalMilliseconds;

			double currentTimePerFrame = (State == PlayerStates.WALKING ? timePerFrame : timePerRunningFrame);
			if(timer >= currentTimePerFrame) {
				// Advance the frame
				timer = 0.0;

				numberOfFrames = (int)(((float)texture.Width) / width);
				currentFrame = (currentFrame < numberOfFrames - 1 ? currentFrame + 1 : 0);
			}
		}

		public override void Draw(GameTime gameTime, SpriteBatch spriteBatch, Color? color = null) {
			if(texture == null) return;

			if(State == PlayerStates.DEAD) {
				/* Height and Width are reversed for the dead sprite
				 * because it is laying down */
				var spriteRect = new Rectangle(
					0,
					height,
					height,
					width
				);

				spriteBatch.Draw(texture, new Rectangle(x, y + (height - width), height, width), spriteRect, (color.HasValue ? color.Value : Color.White));
			} else {
				var spriteRect = new Rectangle(
					currentFrame * width,
					0,
					width,
					height
				);

				spriteBatch.Draw(texture, new Rectangle(x, y, width, height), spriteRect, (color.HasValue ? color.Value : Color.White));
			}
		}
	}
}
